// Copyright (c) 2002 Cunningham & Cunningham, Inc.
// Released under the terms of the GNU General Public License version 2 or later.

package eg.music
{
import com.fit4as.fit.ActionFixture;


public class Simulator {

    // This discrete event simulator supports three events
    // each of which is open coded in the body of the simulator.

    public static var system : Simulator = new Simulator();
    public static var time : int = new Date().getTime();

    public static var nextSearchComplete : Number = 0;
    public static var nextPlayStarted : Number = 0;
    public static var nextPlayComplete : Number = 0;

    private function nextEvent(bound : Number) : Number {
        var result : Number = bound;
        result = sooner(result, nextSearchComplete);
        result = sooner(result, nextPlayStarted);
        result = sooner(result, nextPlayComplete);
        return result;
    }

    private function sooner(soon : Number, event : Number) : Number {
        return event > time && event < soon ? event : soon;
    }

    private function perform() : void {
        if (time == nextSearchComplete) {
            MusicLibrary.instance.searchComplete();
        }
        if (time == nextPlayStarted) {
            MusicPlayer.playStarted();
        }
        if (time == nextPlayComplete) {
            MusicPlayer.playComplete();
        }
    }

    private function advance(future : Number) : void {
        while (time < future) {
            time = nextEvent(future);
            perform();
        }
    }

    public static function schedule(seconds : Number) : Number {
        return time + Math.floor(1000 * seconds);
    }

    public function delay(seconds : Number) : void {
        advance(schedule(seconds));
    }

    public function waitSearchComplete() : void {
        advance(nextSearchComplete);
    }

    public function waitPlayStarted() : void {
        advance(nextPlayStarted);
    }

    public function waitPlayComplete() : void {
        advance(nextPlayComplete);
    }

    public function failLoadJam() : void {
        ActionFixture.actor = new Dialog("load jamed", ActionFixture.actor);
    }


}
}